package com.example.productmanagerspringboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.productmanagerspringboot.data.entity.MyUser;
import com.example.productmanagerspringboot.data.pojo.LoginUser;
import com.example.productmanagerspringboot.mapper.UserMapper;
import com.example.productmanagerspringboot.utils.RedisTokenManager;
import com.example.productmanagerspringboot.utils.UserRedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
    private final UserMapper mapper;
    private final UserRedisUtils userRedisUtils;

    public MyUserDetailsService(UserMapper mapper, UserRedisUtils userRedisUtils) {
        this.mapper = mapper;
        this.userRedisUtils = userRedisUtils;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        //从数据库获取用户信息
        MyUser myUser = mapper.selectOne(queryWrapper);
        if (myUser == null) throw new UsernameNotFoundException(username + "找不到");
        List<String> authorities = new ArrayList<>();
        authorities.add(myUser.getType());
        userRedisUtils.setUserId(myUser.getUsername(), myUser.getId());
        System.out.println("authorities:" + myUser.getType());
        //封装用户信息，用于认证与密码校验；加密密码
        return new LoginUser(username, new BCryptPasswordEncoder().encode(myUser.getPassword()), authorities);
    }
}
